package com.zz.yt.lib.annex.document;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.net.RestClient;
import com.whf.android.jar.net.callback.IError;
import com.whf.android.jar.net.callback.IFailure;
import com.whf.android.jar.net.callback.ISuccess;
import com.whf.android.jar.util.log.LatteLogger;
import com.zz.yt.lib.annex.BitmapUtils;
import com.zz.yt.lib.annex.QbSdkUtils;
import com.zz.yt.lib.annex.R;
import com.zz.yt.lib.annex.document.adapter.AnnexAdapter;
import com.zz.yt.lib.annex.document.bean.AnnexBean;
import com.zz.yt.lib.annex.document.constants.AnnexKeys;
import com.zz.yt.lib.annex.document.util.AnnexUtil;
import com.zz.yt.lib.annex.listener.OnClickAnnexCallback;
import com.zz.yt.lib.annex.listener.OnClickAnnexListener;
import com.zz.yt.lib.annex.listener.OnClickAnnexLoading;
import com.zz.yt.lib.annex.listener.OnClickPictureCallback;
import com.zz.yt.lib.annex.loader.ImageLoaderArrayUtils;
import com.zz.yt.lib.annex.path.IRestClientPath;
import com.zz.yt.lib.annex.popup.utils.PictureAnnexPopupUtils;
import com.zz.yt.lib.annex.popup.utils.PicturePopupUtils;
import com.zz.yt.lib.annex.constant.PictureConstant;

import java.util.ArrayList;
import java.util.List;

/**
 * 文件列表(doc,pdf等)
 *
 * @author qf
 * @version 2020-04-08
 */
public class DocumentView extends RelativeLayout implements OnClickAnnexListener, OnClickPictureCallback,
        ISuccess, IFailure, IError {

    private final Context context;
    private final TextView mTextView;
    private final ImageView mImageView;
    private final RecyclerView mRecyclerView;
    private final RelativeLayout mRelativeLayout;
    private final AnnexAdapter mAnnexAdapter = new AnnexAdapter();

    /*** 可选择文件数量*/
    private int maxCount = 9;

    /*** 选择文件类型 */
    private int typeDocument;
    private boolean isAdded;
    private final boolean isCompress;
    private final int afterWidth;
    private final int afterHeight;
    private Fragment mFragment = null;
    private Activity mActivity = null;
    private boolean preview = true;
    private String previewHint = "";

    /*** 预览点击进度*/
    private OnClickAnnexLoading mClickAnnexLoading = null;

    /*** 预览点击事件*/
    private OnClickAnnexListener mClickAnnexListener = null;

    /*** 图片选择回调*/
    private OnClickPictureCallback mClickPictureCallback = null;

    /*** 图片选择回调 */
    private View.OnClickListener mClickBackListener = null;

    /*** 上传回调 */
    private IRestClientPath mRestClientPath = null;

    private ActivityResultLauncher<Intent> resultLauncher;

    public DocumentView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        // 加载布局
        LayoutInflater.from(context).inflate(R.layout.haian_view_document_picture, this, true);
        TextView mTextMust = findViewById(R.id.img_image);
        mTextView = findViewById(R.id.id_text_document);
        mImageView = findViewById(R.id.id_image_document);
        mRecyclerView = findViewById(R.id.recyclerview);
        mRelativeLayout = findViewById(R.id.id_layout_document);
        final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.DocumentView);
        //是否是必传，默认是true
        final boolean isMust = attributes.getBoolean(R.styleable.DocumentView_isMust, true);
        if (mTextMust != null) {
            mTextMust.setVisibility(isMust ? VISIBLE : GONE);
        }
        //选择文件类型
        String titleDocument = attributes.getString(R.styleable.DocumentView_titleDocument);
        if (!TextUtils.isEmpty(titleDocument) && mTextView != null) {
            mTextView.setText(titleDocument);
        }
        //选择文件类型
        typeDocument = attributes.getInt(R.styleable.DocumentView_typeDocument, PictureConstant.CAMERA);
        //是否显示添加按钮
        isAdded = attributes.getBoolean(R.styleable.DocumentView_isAdded, true);
        mRelativeLayout.setVisibility(isAdded ? VISIBLE : GONE);
        if (isAdded) {
            mImageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mClickBackListener != null) {
                        mClickBackListener.onClick(DocumentView.this);
                    }
                    switch (typeDocument) {
                        case PictureConstant.ALL:
                            PictureAnnexPopupUtils.create(DocumentView.this)
                                    .setMaxCount(maxCount - getData().size())
                                    .setResultLauncher(resultLauncher)
                                    .setContent(mActivity)
                                    .setContent(mFragment)
                                    .popup();
                            break;
                        case PictureConstant.GALLERY:
                            PicturePopupUtils.create(DocumentView.this)
                                    .setMaxCount(maxCount - getData().size())
                                    .setContent(mActivity)
                                    .setContent(mFragment)
                                    .popup();
                            break;
                        default:
                            setFile();
                            break;
                    }
                }
            });
        }
        //
        final boolean isDelete = attributes.getBoolean(R.styleable.DocumentView_isDelete, true);
        mAnnexAdapter.setDelete(isDelete);
        mAnnexAdapter.setOnAnnexCallback(new OnClickAnnexCallback() {
            @Override
            public void remove(int position) {
                mAnnexAdapter.removeAt(position);
                if (mClickPictureCallback != null) {
                    mClickPictureCallback.remove(position);
                }
            }
        });
        mAnnexAdapter.setOnClickAnnexListener(this);
        mRecyclerView.setAdapter(mAnnexAdapter);
        mAnnexAdapter.setList(new ArrayList<AnnexBean>());

        isCompress = attributes.getBoolean(R.styleable.DocumentView_isCompress, false);
        afterWidth = attributes.getInteger(R.styleable.DocumentView_afterWidth, 1080);
        afterHeight = attributes.getInteger(R.styleable.DocumentView_afterHeight, 1920);

        //列表显示
        LinearLayoutManager manager = new LinearLayoutManager(context);
        mRecyclerView.setLayoutManager(manager);
        //其他属性

        attributes.recycle();
    }

    private void setFile() {
        if (resultLauncher != null) {
            AnnexUtil.Bundle()
                    .setMaxCount(maxCount - getData().size())
                    .setResultLauncher(resultLauncher)
                    .onAddAnnexClickListener();
            return;
        }
        if (mFragment != null) {
            AnnexUtil.Bundle()
                    .setMaxCount(maxCount - getData().size())
                    .setContent(mFragment)
                    .onAddAnnexClickListener();
            return;
        }
        AnnexUtil.Bundle()
                .setMaxCount(maxCount - getData().size())
                .setContent(mActivity != null ? mActivity : Latte.getActivity())
                .onAddAnnexClickListener();
    }

    /**
     * @param resultLauncher:api的直接回调方法，处理下文件的那个回调
     */
    public void setActivityResultLauncher(ActivityResultLauncher<Intent> resultLauncher) {
        this.resultLauncher = resultLauncher;
    }

    public void setTitle(CharSequence text) {
        if (mTextView != null) {
            mTextView.setText(text);
        }
    }

    public String getTitle() {
        if (mTextView != null) {
            return mTextView.getText().toString();
        }
        return "";
    }

    /**
     * @param mRestClientPath:上传回调
     */
    public void setRestClientPath(IRestClientPath mRestClientPath) {
        this.mRestClientPath = mRestClientPath;
    }

    public void setContext(Fragment fragment) {
        this.mFragment = fragment;
    }

    public void setContext(Activity activity) {
        this.mActivity = activity;
    }

    public void onActivityResult(ActivityResult result) {
        LatteLogger.i("onActivityResult");
        if (result != null) {
            final List<String> annex = AnnexUtil.onResultList(result);
            if(annex.size() == 0){
                return;
            }
            //不直接添加在控件中、上传后通过addData添加。
            if (mRestClientPath != null) {
                mRestClientPath.setSelect(annex, new IRestClientPath.OnClickAnnexCallback() {
                    @Override
                    public void filePath(List<AnnexBean> filePath) {
                        if (filePath != null) {
                            for (AnnexBean pathBean : filePath) {
                                addData(pathBean);
                            }
                        }
                    }
                });
            } else {
                for (String str : annex) {
                    addData(new AnnexBean(str));
                }
            }
        }
    }

    public void setMaxCount(int maxCount) {
        this.maxCount = maxCount;
    }

    /***
     * 不可以查看文件
     * @param preview：提示不可以查看文件的理由。
     */
    public void setPreview(String preview) {
        this.preview = false;
        this.previewHint = preview;
    }

    /***
     * 设置图片回调
     * @param callback：
     */
    public void setClickPictureCallback(OnClickPictureCallback callback) {
        this.mClickPictureCallback = callback;
    }

    /***
     * 主界面
     * @param typeDocument：文件类型
     */
    public void setRootView(@PictureConstant.Photograph int typeDocument) {
        this.typeDocument = typeDocument;
    }

    /***
     * 预览是下载进度条
     * @param listener：
     */
    public void setOnClickAnnexLoading(OnClickAnnexLoading listener) {
        this.mClickAnnexLoading = listener;
    }

    /***
     * 预览点击事件
     * @param listener：
     */
    public void setOnClickAnnexListener(OnClickAnnexListener listener) {
        this.mClickAnnexListener = listener;
    }

    public void setEdit(boolean isEdit) {
        isAdded = isEdit;
        mRelativeLayout.setVisibility(isAdded ? VISIBLE : GONE);
        mAnnexAdapter.setDelete(isEdit);
    }

    /**
     * @param isEdit：焦点
     */
    public void setFocus(boolean isEdit) {
        isAdded = isEdit;
        mImageView.setVisibility(isAdded ? VISIBLE : GONE);
        mAnnexAdapter.setDelete(isEdit);
    }

    /***
     * 展示附件
     * @param result：附件
     */
    public void setData(List<AnnexBean> result) {
        mAnnexAdapter.setList(new ArrayList<AnnexBean>());
        for (AnnexBean annexBean : result) {
            addData(annexBean);
        }
    }

    /***
     * 添加附件
     * @param annexBean：添加附件
     */
    public void addData(AnnexBean annexBean) {
        mAnnexAdapter.addData(BitmapUtils.compressIMG(getContext(), annexBean, isCompress,
                afterWidth, afterHeight, true));
    }

    public ImageView getImageView() {
        return mImageView;
    }

    public RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    public RelativeLayout getRelativeLayout() {
        return mRelativeLayout;
    }

    public List<AnnexBean> getData() {
        if (mAnnexAdapter == null) {
            return new ArrayList<>();
        }
        return mAnnexAdapter.getData();
    }

    public List<Object> getDataValue() {
        final List<Object> objectList = new ArrayList<>();
        List<AnnexBean> dataList = getData();
        for (AnnexBean annexBean :
                dataList) {
            objectList.add(annexBean.getValue());
        }
        return objectList;
    }

    public AnnexAdapter getAdapter() {
        return mAnnexAdapter;
    }

    @Override
    public void onClickAnnex(int type, AnnexBean item) {
        if (!preview) {
            if (mClickAnnexListener != null) {
                mClickAnnexListener.onClickAnnex(type, item);
                return;
            }
            ToastUtils.showShort(previewHint);
            return;
        }
        if (item.getType() == AnnexKeys.IMAGE || item.getType() == AnnexKeys.JPG) {
            LatteLogger.i("IMG");
            List<Object> objectList = new ArrayList<>();
            List<AnnexBean> annexBeans = getData();
            for (AnnexBean bean : annexBeans) {
                if (bean.getType() == AnnexKeys.IMAGE || bean.getType() == AnnexKeys.JPG) {
                    objectList.add(bean.getPath());
                }
            }
            ImageLoaderArrayUtils.create(null, objectList)
                    .setCurrentPosition(objectList.indexOf(item.getPath()))
                    .show();
        } else {
            final boolean isNet = URLUtil.isNetworkUrl(item.getPath()) || URLUtil.isAssetUrl(item.getPath());
            if (!isNet) {
                int s = QbSdkUtils.openFileReader(context, item, null, null);
                LatteLogger.i("QbSdk: " + s);
            } else {
                if (mClickAnnexLoading != null) {
                    mClickAnnexLoading.showLoading();
                }
                RestClient.builder()
                        .url(item.getPath())
                        .name(item.getFileName())
                        .failure(this)
                        .success(this)
                        .error(this)
                        .build()
                        .download();
            }
        }
    }

    @Override
    public void onCallback(List<String> selectList) {
        if (mClickPictureCallback != null) {
            mClickPictureCallback.onCallback(BitmapUtils.compressIMG(context, selectList, isCompress, afterWidth, afterHeight));
        }
    }

    @Override
    public void setOnClickListener(@Nullable OnClickListener callback) {
        this.mClickBackListener = callback;
    }

    @Override
    public void remove(int position) {
        if (mClickPictureCallback != null) {
            mClickPictureCallback.remove(position);
        }
    }

    @Override
    public void onSuccess(String response) {
        LatteLogger.i("" + response);
        if (mClickAnnexLoading != null) {
            mClickAnnexLoading.hideLoading();
        }
        QbSdkUtils.openFileReader(context, response, null, null);
    }

    @Override
    public void onError(int code, String msg) {
        LatteLogger.e(msg);
        if (mClickAnnexLoading != null) {
            mClickAnnexLoading.hideLoading();
        }
    }

    @Override
    public void onFailure() {
        if (mClickAnnexLoading != null) {
            mClickAnnexLoading.hideLoading();
        }
    }

}
